#!/usr/bin/env bash

# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0

# run_dir_limiter does what the name suggests - often, when tests are run multiple times, the number
# of run directories created might end up getting large. This script finds and deletes N oldest
# directories in a given path P, where P and N are the arguments to this script respedtively

usage="Error: usage: $0 [path-to-run-dir] [num-run-dir-limit]";
# need exactly 2 args, 1st needs to be the path and 2nd, a number
if [[ $# -ne 2 || ! -d $1 || ! $2 =~ ^[0-9]+$ ]]; then
  echo $usage
  exit 1;
fi

run_dir=$(realpath $1);
find_cmd="find $run_dir -mindepth 1 -maxdepth 1 -type d";
num_dirs=$($find_cmd | wc -l);
num_rm_dirs=$(($num_dirs - $2));
if [[ $num_rm_dirs -gt 0 ]]; then
  dirs=$($find_cmd -printf '%T+ %p\n' | sort | head -n $num_rm_dirs | awk '{print $2}');
  for dir in $dirs; do
    echo "Removing $dir..."
    /bin/rm -rf $dir
  done
fi
